/*@Copyright (c) 2025 stray
 *@author		:	stray
 *@date			:	2025-06-05
 *@usage		:
 ********************************************************************/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QFileDialog>
#include<QPushButton>
#include<QDir>
#include<QMessageBox>
#include<QDebug>
#include<sstream>
#include<QDateTime>

#define mydebug 1

//默认数据库名称
#define DEF_DB_NAME "/home/lystar/qt_ws/plc_upper/db/plc.db"
//默认连接名称
#define DEF_CN_NAME "plc_db"
//默认用户名称，密码
#define DEF_USER_NAME "PLC_LIU"
#define DEF_PSK "123456"

//默认打开目录为用户空间目录
#if mydebug
#define DEF_FILE_PATH "/home/lystar/qt_ws/plc_upper/form"
#else
#define DEF_FILE_PATH QDir::homePath()
#endif

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    list_line=0;
    QCoreApplication::addLibraryPath("/home/lystar/Qt/6.8.3/gcc_64/plugins");

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(DEF_DB_NAME);



    //设置列表格式
    model_list = new QStandardItemModel(this);
    set_tabel_view();

    //槽函数
    connect(this->ui->pushButton_select_excel,&QPushButton::clicked,this,&MainWindow::slot_select_xlsx);

}


void MainWindow::db_add_part(const PARTS &part){

}

void MainWindow::slot_select_xlsx(){
    //this：父窗口指针。tr("打开文件")：对话框标题。"."：默认打开的目录。tr("Text Files (*.txt);;All Files (*)")：文件过滤器。
    QString filePath = QFileDialog::getOpenFileName(this,tr("选择文件"),DEF_FILE_PATH,tr("XLSX Files (*.xlsx);;All Files (*)"));
    //取消选择情况
    if(filePath == ""){
        return;
    }

    this->ui->label_latest_excel_name->setText(filePath);
    //打开文件
    if(!open_doc(filePath.toUtf8().constData())){
        QMessageBox::critical(this,"文件打开失败","请检查文件是否损坏");
        return;
    }
    //打开数据库
    if(!db.isOpen()){
        db.open();
    }
    if(db.isOpen()){
        QMessageBox::information(this,"成功","数据库打开成功");
    }
    qDebug()<<db.lastError();
    qDebug()<<db.tables()<<"\n";

    //解析
    this->parse_doc();

    //关闭数据库
    if(db.isOpen()){
        db.close();
    }
    if(doc.isOpen()){
        doc.close();
    }
}


MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::open_doc(std::string fn){
    this->doc.open(fn);
    if(doc.isOpen()){
        QMessageBox::information(this,"打开成功","文件成功打开");
        return true;
    }
    else{
        QMessageBox::warning(this,"打开失败","请检查文件权限或占用情况");
        return false;
    }
    return false;
}

bool MainWindow::parse_doc(){
    ox::XLWorksheet wks = doc.workbook().sheet(1);
    for(int excel_line=3;excel_line<100;excel_line++){
        PARTS part;
        std::stringstream ss;
        ss<<excel_line;
        std::string num = ss.str();
        if(!wks.cell(std::string("A")+num).empty())
        {
            part.name = wks.cell(std::string("C")+num).getString();
            if(part.name == ""){
                continue;
            }
            model_list->setItem(list_line,0,new QStandardItem(QString::fromStdString(part.name)));
            std::string tempstr;
            //解析完成后加载数据到列表中
            tempstr = wks.cell(std::string("D")+num).getString();
            model_list->setItem(list_line,1,new QStandardItem(QString::fromStdString(tempstr)));
            part.remained_num = part.total_num = stof(tempstr);
            part.completed_num = 0;
            tempstr = wks.cell(std::string("E")+num).getString();
            model_list->setItem(list_line,2,new QStandardItem(QString::fromStdString(tempstr)));
            part.MD = stof(tempstr);

            tempstr = wks.cell(std::string("F")+num).getString();
            model_list->setItem(list_line,3,new QStandardItem(QString::fromStdString(tempstr)));
            part.MThick = stof(tempstr);

            tempstr = wks.cell(std::string("G")+num).getString();
            model_list->setItem(list_line,4,new QStandardItem(QString::fromStdString(tempstr)));
            part.MLength = stof(tempstr);

            tempstr = wks.cell(std::string("H")+num).getString();
            model_list->setItem(list_line,5,new QStandardItem(QString::fromStdString(tempstr)));
            part.BD = stof(tempstr);

            tempstr = wks.cell(std::string("I")+num).getString();
            model_list->setItem(list_line,6,new QStandardItem(QString::fromStdString(tempstr)));
            part.BY = stof(tempstr);

            tempstr = wks.cell(std::string("J")+num).getString();
            model_list->setItem(list_line,7,new QStandardItem(QString::fromStdString(tempstr)));
            part.BRotX = stof(tempstr);

            tempstr = wks.cell(std::string("K")+num).getString();
            model_list->setItem(list_line,8,new QStandardItem(QString::fromStdString(tempstr)));
            part.BRotY = stof(tempstr);

            tempstr = wks.cell(std::string("L")+num).getString();
            model_list->setItem(list_line,9,new QStandardItem(QString::fromStdString(tempstr)));
            part.ThroughAll = (bool)stoi(tempstr);

            tempstr = wks.cell(std::string("M")+num).getString();
            model_list->setItem(list_line,10,new QStandardItem(QString::fromStdString(tempstr)));
            part.LeftRotA = (bool)stoi(tempstr);

            tempstr = wks.cell(std::string("N")+num).getString();
            model_list->setItem(list_line,11,new QStandardItem(QString::fromStdString(tempstr)));
            part.RightRotA = (bool)stoi(tempstr);

            tempstr = wks.cell(std::string("O")+num).getString();
            model_list->setItem(list_line,12,new QStandardItem(QString::fromStdString(tempstr)));
            part.BX = stof(tempstr);

            tempstr = wks.cell(std::string("P")+num).getString();
            model_list->setItem(list_line,13,new QStandardItem(QString::fromStdString(tempstr)));
            part.LabelText = tempstr;
            ++list_line;

            // QSqlQuery sql_query(db);
            // QString insert_sql = "insert into test_tb values (?, ?, ?)";
            // sql_query.prepare(insert_sql);
            // sql_query.addBindValue(32);
            // sql_query.addBindValue("noreally");
            // // sql_query.addBindValue(1);

            //载入数据库
            QSqlQuery sql_query(db);
            QString insert_sql = "insert into parts values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            sql_query.prepare(insert_sql);
            sql_query.addBindValue(part.name.c_str());
            sql_query.addBindValue(part.total_num);
            sql_query.addBindValue(part.remained_num);
            sql_query.addBindValue(part.completed_num);
            sql_query.addBindValue(part.MD);
            sql_query.addBindValue(part.MThick);
            sql_query.addBindValue(part.MLength);
            sql_query.addBindValue(part.BD);
            sql_query.addBindValue(part.BY);
            sql_query.addBindValue(part.BRotX);
            sql_query.addBindValue(part.BRotY);
            sql_query.addBindValue(part.ThroughAll);
            sql_query.addBindValue(part.LeftRotA);
            sql_query.addBindValue(part.RightRotA);
            sql_query.addBindValue(part.BX);
            sql_query.addBindValue(part.LabelText.c_str());
            sql_query.addBindValue(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            sql_query.addBindValue("no");
            // qDebug()<<sql_query.boundValues()<<"\n";

            if(!sql_query.exec()){
                qDebug()<<"[error]"<<db.lastError()<<"\n";
            }

        }
        else
        {
            continue;
        }
    }
    doc.save();
    doc.close();
    ui->tableView->setModel(model_list);
    return true;
}





/*@usage		:	设置展示列表表头
*@author		:	stray	2025-06-05
********************************/
void MainWindow::set_tabel_view(){
    model_list->setColumnCount(14);
    model_list->setHorizontalHeaderItem(0,new QStandardItem("零件名称"));
    model_list->setHorizontalHeaderItem(1,new QStandardItem("数量"));
    model_list->setHorizontalHeaderItem(2,new QStandardItem("直径"));
    model_list->setHorizontalHeaderItem(3,new QStandardItem("厚度"));
    model_list->setHorizontalHeaderItem(4,new QStandardItem("长度"));
    model_list->setHorizontalHeaderItem(5,new QStandardItem("相贯孔径"));
    model_list->setHorizontalHeaderItem(6,new QStandardItem("孔位置"));
    model_list->setHorizontalHeaderItem(7,new QStandardItem("孔X转角"));
    model_list->setHorizontalHeaderItem(8,new QStandardItem("孔Y转角"));
    model_list->setHorizontalHeaderItem(9,new QStandardItem("贯穿"));
    model_list->setHorizontalHeaderItem(10,new QStandardItem("坡口1"));
    model_list->setHorizontalHeaderItem(11,new QStandardItem("坡口2"));
    model_list->setHorizontalHeaderItem(12,new QStandardItem("孔偏心"));
    model_list->setHorizontalHeaderItem(13,new QStandardItem("喷码"));
    ui->tableView->setModel(model_list);
}

